package com.example.demo.controller;

import com.example.demo.service.GetUserListService;
import com.example.demo.utils.Md5Utils;
import com.example.demo.utils.Result;
import com.example.demo.utils.ResultUtil;
import com.example.demo.vo.Page;
import com.example.demo.vo.ResultList;
import com.example.demo.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/api")
@ResponseBody
public class GetUser {

    @Autowired
    public GetUserListService getUserListService;

    @GetMapping("/user")
    public Result getUserList(){
        List<User> user = getUserListService.getUserList();
        return ResultUtil.success(user);
    }

    @GetMapping("/userList")
    ResultList getUserListLimt(Page page){
        ResultList user = new ResultList();
        try {
            user.setCode(0);
            if("0".equals(String.valueOf(page.getPageNum())) || page.getPageNum() <=0){
                user.setData(getUserListService.getUserList());
            }else{
                user.setData(getUserListService.getUserListLimt(page));
            }
        } catch (Exception e) {
            user.setCode(1);
            user.setMsg("数据异常");
        }

        return user;
    }

    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user){
        user.setPassWord(Md5Utils.code(user.getPassWord()));
        int result = getUserListService.addUser(user);
        if(result >=1 ){
            return ResultUtil.success();
        }else{
            return ResultUtil.error(1,"添加失败");
        }
    }

    @PutMapping("/update")
    public Result updateUser(@RequestBody User user){
        int result = getUserListService.updateUser(user);
        if(result >=1 ){
            return ResultUtil.success();
        }else{
            return ResultUtil.error(1,"添加失败");
        }
    }

    @DeleteMapping("/del")
    public Result delUser(int id){
        int result = getUserListService.delUser(id);
        if(result >=1 ){
            return ResultUtil.success();
        }else{
            return ResultUtil.error(1,"添加失败");
        }
    }
}
